package leetcode.newVersion.subArray;

import java.util.ArrayList;
import java.util.HashMap;

public class lc560 {
    /*
    以前缀和的方法解题
     */
    public int subarraySum(int[] nums, int k) {
       HashMap<Integer, Integer> map = new HashMap<>();//key是前缀和，value是每个前缀和出现的次数
        map.put(0,1);//第0个元素的前缀和为0,出现一次
        int tmpSum = 0;
        int ans = 0;

        for (int i = 0; i < nums.length; i++) {
            tmpSum += nums[i];
            if (map.containsKey(tmpSum - k)) {
                ans += map.get(tmpSum - k);
            }
            map.put(tmpSum, map.getOrDefault(tmpSum, 0) + 1);
        }

        return ans;
    }

    public static void main(String[] args) {
        lc560 l = new lc560();
        int[] nums1 = new int[] {1, 1, 1};
        int[] nums2 = new int[] {1, 2, 3};
        System.out.println(l.subarraySum(nums1, 2));
        System.out.println(l.subarraySum(nums2, 3));
    }
}
